const app = getApp()
import Dialog from '@vant/weapp/dialog/dialog';
import {
  showMsg
} from '../../../../utils/config.js'
let spacePopoverSearch = require('../behaviors/space/space-popover-search.js')
let behaviorsOrgSelection = require('../../../../pages/behaviors/org/orgSelection.js')
import {
  reqDeviceStatistics,
  reqDeviceList,
  reqProductList,
  reqDeviceUnBind,
  reqGetByDeviceId,
  reqDefenceupdate,
  reqDeviceReplace,
  reqDeviceByImei,
  reqCheckReplace
} from '../../../../request/api'
Page({
  behaviors: [spacePopoverSearch, behaviorsOrgSelection], //空间弹窗选择混入
  data: {
    navHeight: app.globalData.navHeight + 'px', //头部距离
    bottomHeight: app.globalData.bottomHeight + 'px', //iphone底部距离

    statistics: {
      all: 0,
      online: 0,
      offline: 0,
    },

    dataList: [], //设备列表
    page: 1,
    isNextPage: true,
    triggered: false,
    searchValue: '',

    // 筛选弹窗开始
    showSearch: false, //筛选弹窗
    statusList: [{
      id: '',
      name: '全部',
      active: true,
    }, {
      id: 1,
      name: '在线',
      active: false,
    }, {
      id: 0,
      name: '离线',
      active: false,
    }, ],
    online: '', //选中的设备状态 
    productList: [],
    isAlarmList: [{
      active: false,
      name: "正常",
      id: 0
    }, {
      active: false,
      name: "告警",
      id: 1
    }],
    isAlarm: "",
    productId: '', //选中的产品
    hasSearch: false, //是否有筛选
    minBattery: "", //最小值
    maxBattery: "", //最大值
    // 筛选弹窗结束

    formData: [],
    showDatePicker: false,
    currentDate: '12:00',
    value: [0, 0, 0], // 初始值，分别对应小时、分钟、秒
    hours: Array.from({
      length: 24
    }, (_, i) => i.toString().padStart(2, '0')), // 00-23
    minutes: Array.from({
      length: 60
    }, (_, i) => i.toString().padStart(2, '0')), // 00-59
    seconds: Array.from({
      length: 60
    }, (_, i) => i.toString().padStart(2, '0')), // 00-59
    selectTime: "00:00:00", //选中的时间

    // 更换设备
    newtype: "", //设备类型
    newimei: "", //新设备编码
  },


  onLoad() {
    const result1 = '{"ACT":"Add","DT":"","ID":"AGG0122407RYJY","WiFi":"15"}';
    const result2 = "248001090004";
    const result5 = '3700ac65c25125f2'
    console.log(this.isjson(result1));
    console.log(this.isjson(result2));
    console.log(this.isjson(result5));
    // const result3 = JSON.parse(result1);
    // const result4 = JSON.parse(result2);
    // const result6 = JSON.parse(result5);
    // console.log(JSON.parse(result1));
    // console.log(JSON.parse(result2));
    // console.log(JSON.parse(result5));
    // console.log(this.isJson(result1)); // true  
    // console.log(this.isJson(result2)); // false
    // console.log(typeof (result3));
    // console.log(typeof (result4));
    // console.log(typeof (result3) == 'object');
    // console.log(typeof (result4) == 'number');

    this.getProductList()
    this.getBuildList()
  },
  onShow() {
    // this.getStatistics()
    // this.getInitDataList()// 操作列表后回到最初状态
    this.resetSearch() //重置
  },

  // 单位选择确定
  confirmUnit() {
    let {
      buildList,
      floorList,
      roomList
    } = this.data

    buildList.forEach(item => {
      if (!item.id) {
        item.active = true
      } else {
        item.active = false
      }
    })
    floorList.forEach(item => {
      item.active = false
    })
    roomList.forEach(item => {
      item.active = false
    })

    this.setData({
      buildList,
      floorList: [],
      roomList: [],
      activeSpace: 'build',
      buildId: '',
      floorId: '',
      roomId: '',
      spaceName: '全部',
      spaceId: '',
    })
    this.resetSearch() //重置
  },

  confirmOrg() {
    let {
      buildList,
      floorList,
      roomList
    } = this.data

    buildList.forEach(item => {
      if (!item.id) {
        item.active = true
      } else {
        item.active = false
      }
    })
    floorList.forEach(item => {
      item.active = false
    })
    roomList.forEach(item => {
      item.active = false
    })

    this.setData({
      buildList,
      floorList: [],
      roomList: [],
      activeSpace: 'build',
      buildId: '',
      floorId: '',
      roomId: '',
      spaceName: '全部',
      spaceId: '',
    })
    this.resetSearch() //重置
  },

  // 获取统计数据
  async getStatistics() {
    const res = await reqDeviceStatistics({
      orgId: this.data.orgInfo.orgId,
      online: this.data.online,
      productId: this.data.productId,
      spaceId: this.data.spaceId,
      imei: this.data.searchValue,
      isAlarm: this.data.isAlarm,
      minBattery: this.data.minBattery,
      maxBattery: this.data.maxBattery,
      userId: app.globalData.userId,
      roleName: app.globalData.rolename,
      tenantId: app.globalData.tenantId,
    })
    this.setData({
      statistics: res.data.row
    })
  },

  // 产品列表
  async getProductList() {
    const res = await reqProductList()
    if (res.code !== 20000) return showMsg(res.message)
    let {
      rows
    } = res.data
    rows.unshift({
      id: '',
      name: '全部',
      active: true
    })

    this.setData({
      productList: rows
    })
  },
  /**
   * @name: 获取设备列表
   * @return {*}
   */
  async getDataList() {
    let params = {
      tenantId: app.globalData.tenantId,
      userId: app.globalData.userId,
      roleName: app.globalData.rolename,

      orgId: this.data.orgInfo.orgId,
      online: this.data.online,
      productId: this.data.productId,
      spaceId: this.data.spaceId,
      imei: this.data.searchValue,
      minBattery: this.data.minBattery,
      maxBattery: this.data.maxBattery,
      isAlarm: this.data.isAlarm,
    }
    const res = await reqDeviceList(this.data.page, 10, params)
    if (res.code !== 20000) return showMsg(res.message)
    let {
      rows
    } = res.data
    let {
      productList
    } = this.data
    if (rows && rows.length) {
      rows.forEach(item => {
        productList.forEach(citem => {
          if (item.deviceType === citem.deviceType) {
            item.type = citem.name //产品类型
            item.pic = citem.pic
          }
        })
      });
    }
    console.log(rows);
    if (this.data.page === 1) {
      console.log(1111);
      this.setData({
        dataList: rows,
        isNextPage: true
      })
    } else if (this.data.page > 1 && rows.length) {
      this.setData({
        dataList: this.data.dataList.concat(rows),
        isNextPage: true
      })
    } else if (this.data.page > 1 && !rows.length) {
      showMsg('已经到底啦~')
      this.setData({
        isNextPage: false
      })
    }
  },
  // 滚动到底部触发
  lower() {
    if (!this.data.isNextPage) return
    this.setData({
      page: this.data.page + 1,
    })
    this.getDataList()
  },
  // 下拉刷新
  async onRefresh() {
    this.setData({
      // dataList: [],
      page: 1,
      isNextPage: true,
      triggered: true,
    })
    await this.getDataList()
    this.setData({
      triggered: false,
    })
  },
  // 操作列表后回到最初状态
  getInitDataList() {
    this.setData({
      page: 1,
      isNextPage: true,
      // dataList: []
    })
    this.getDataList()
  },

  // 输入框搜索
  searchChange(e) {
    // e.detail='11'
    // e.detail = e.detail.replace(/[^0-9]/g, '');
    e.detail = e.detail.replace(/[\u4e00-\u9fa5]/g, '');
    console.log(e.detail);
    // 防止输入字母也触发接口调用
    if (this.data.searchValue2 == e.detail) {
      this.setData({
        searchValue: e.detail,
        searchValue2: e.detail,
      })
      return;
    }
    this.setData({
      searchValue: e.detail,
      searchValue2: e.detail,
    })
    clearTimeout(this.data.timer)
    this.data.timer = setTimeout(() => {
      this.getInitDataList()
      this.getStatistics()
    }, 1000)
  },
  // js判断字符串是否为JSON格式
  isjson(str) {
    if (typeof str == 'string') {
      try {
        var obj = JSON.parse(str);
        if (typeof obj == 'object' && obj) {
          return true;
        } else {
          return false;
        }
      } catch (e) {
        console.log('error：' + str + '!!!' + e);
        return false;
      }
    }
    console.log('It is not a string!')
  },
  // 点击扫码获取imei
  imeiScan() {
    const that = this
    let qrcode = ''
    wx.scanCode({
      success(res) {
        qrcode = res.result;
        // console.log(qrcode);
        if (!qrcode) return showMsg('扫描失败，请重新扫描')
        if (qrcode.length >= 3) {
          if (that.isjson(qrcode)) {
            const result = JSON.parse(qrcode);
            // JSON字符格式
            that.setData({
              searchValue: result.ID, //威视达康摄像机取值，后续看需求更改 lc
            })
            clearTimeout(that.data.timer)
            that.data.timer = setTimeout(() => {
              that.getInitDataList()
            }, 500)
          } else {
            // 非JSON格式
            that.setData({
              searchValue: qrcode,
            })
            clearTimeout(that.data.timer)
            that.data.timer = setTimeout(() => {
              that.getInitDataList()
            }, 500)
          }
        } else {
          showMsg('扫描失败，请重新扫描')
          return
        }
      }
    })
  },
  // 点击筛选
  clickSearch() {
    this.setData({
      showSearch: true
    })
  },
  // 点击关闭筛选
  closeSearch() {
    this.setData({
      showSearch: false
    })
  },
  // 点击设备状态
  statusClick(e) {
    let {
      id
    } = e.currentTarget.dataset
    let {
      statusList
    } = this.data
    statusList.forEach(item => {
      if (item.id === id) {
        item.active = true
      } else {
        item.active = false
      }
    })
    this.setData({
      statusList,
      online: id
    })
  },
  // 点击产品类型
  typeClick(e) {
    let {
      id
    } = e.currentTarget.dataset
    let {
      productList
    } = this.data
    productList.forEach(item => {
      if (item.id === id) {
        item.active = true
      } else {
        item.active = false
      }
    })
    this.setData({
      productList,
      productId: id
    })
  },
  // 点击告警状态
  isAlarmClick(e) {
    let {
      id
    } = e.currentTarget.dataset;
    console.log(id);
    let {
      isAlarmList
    } = this.data
    isAlarmList.forEach(item => {
      if (item.id === id) {
        item.active = true
      } else {
        item.active = false
      }
    })
    this.setData({
      isAlarmList,
      isAlarm: id
    })
  },
  // 重置筛选
  resetSearch() {
    let {
      statusList,
      productList,
      isAlarmList
    } = this.data
    statusList.forEach(item => {
      if (item.id === '') {
        item.active = true
      } else {
        item.active = false
      }
    })
    productList.forEach(item => {
      if (item.id === '') {
        item.active = true
      } else {
        item.active = false
      }
    })
    isAlarmList.forEach(item => {
      item.active = false
    })
    this.setData({
      statusList,
      online: '',
      productList,
      isAlarmList,
      isAlarm: "",
      productId: '',
      minBattery: "",
      maxBattery: ""
    })
    this.confirmSearch()
  },
  // 确定筛选点击
  confirmSearch() {
    let {
      online,
      productId,
      isAlarm,
      minBattery,
      maxBattery
    } = this.data;
    let hasSearch = false;
    hasSearch = ((typeof (online) === 'number') || productId || isAlarm || minBattery || maxBattery) ? true : false
    this.setData({
      showSearch: false,
      hasSearch
    })
    this.getStatistics()
    this.getInitDataList()
  },

  // 点击去新增空间
  goAddSpace() {
    let {
      build,
      floor,
      room
    } = this.data

    wx.navigateTo({
      url: '/packageA/pages/index-inside-page/building-add/building-add',
    })
  },
  // 去新增设备
  goAddDevice() {
    // 如果有建筑物筛选且筛选到安装点，则新增时给一个快捷安装点
    let {
      roomId,
      spaceName
    } = this.data
    let params = {
      spaceId: roomId,
      spaceName
    }
    let info = JSON.stringify(params)
    wx.navigateTo({
      url: `/packageA/pages/index-inside-page/device-add/device-add?info=${info}`,
    })
  },
  // 去设备详情
  goDeviceDetail(e) {
    let {
      item
    } = e.currentTarget.dataset
    let info = JSON.stringify(item)
    console.log(item);
    if (item.classMark == 'V380') {
      // 宏视
      wx.navigateTo({
        url: `/packageA/pages/index-inside-page/macrovision-camera/macrovision-camera?info=${info}`,
      })
      return;
    } else if (item.protocol == '4') {
      // 萤石云
      // wx.navigateTo({
      //     url: `/pages/index-inside-page/device-camera2/device-camera2?info=${info}`,
      // })
      wx.navigateTo({
        url: `/packageA/pages/index-inside-page/live/live?info=${info}`,
      })
      return;
    }
    wx.navigateTo({
      url: `/packageA/pages/index-inside-page/device-detailed/device-detailed?info=${info}`,
    })
    // return;
    // if (item.deviceType == 'Camera') {
    //     if (item.classMark == 'V380') {
    //         // 宏视
    //         wx.navigateTo({
    //             url: `/packageA/pages/index-inside-page/macrovision-camera/macrovision-camera?info=${info}`,
    //         })
    //         return;
    //     }
    //     if (item.deviceMac == "" && item.manufacturerId != '1660554046491635714')
    //         return showMsg('设备MAC地址为空')
    //     if (item.manufacturerId == '1660554046491635714') {
    //         // 萤石云
    //         wx.navigateTo({
    //             url: `/pages/index-inside-page/device-camera2/device-camera2?info=${info}`,
    //         })
    //     } else {
    //         // 视洞
    //         wx.navigateTo({
    //             url: `/pages/index-inside-page/device-camera/device-camera?info=${info}`,
    //         })
    //     }
    // } else {
    //     wx.navigateTo({
    //         url: `/packageA/pages/index-inside-page/device-detailed/device-detailed?info=${info}`,
    //     })
    // }
  },

  // 点击复制imei
  clickCopyImei(e) {
    let {
      imei
    } = e.currentTarget.dataset
    wx.setClipboardData({
      data: imei,
      success(res) {
        wx.getClipboardData({
          success(res) {
            showMsg(`设备编码已复制`)
          }
        })
      }
    })
  },
  validateNumber(val) {
    return val.replace(/\D/g, '')
  },
  minBatteryChange(e) {
    // console.log(e);
    let value = this.validateNumber(e.detail.value)
    if (value > 100) {
      value = 100
    }
    this.setData({
      minBattery: value
    })
  },
  maxBatteryChange(e) {
    // console.log(e);
    let value = this.validateNumber(e.detail.value)
    if (value > 100) {
      value = 100
    }
    this.setData({
      maxBattery: value
    })
  },
  // 点击删除设备
  clickDelete(e) {
    let id = e.currentTarget.dataset.id;
    console.log(id);
    Dialog.confirm({
        title: '温馨提示',
        message: '此操作将拆除该设备，是否继续？',
      })
      .then(async () => {
        const res = await reqDeviceUnBind({
          id: id ? id : this.data.listItemInfo.id,
          userId: app.globalData.userId
        })
        if (res.code != 20000) return showMsg(res.message);
        await this.getInitDataList()
        await this.getStatistics()
        showMsg("拆除成功")
        this.unShowMoreActions()
      })
      .catch(() => {});
  },
  // 点击更多操作
  clickMore(e) {
    let {
      item
    } = e.currentTarget.dataset
    this.setData({
      listItemInfo: item,
      showMoreActions: true
    })
  },
  // 点击xx
  closeMoreActions() {
    this.unShowMoreActions()
  },
  // 隐藏更多操作弹窗
  unShowMoreActions() {
    this.setData({
      showMoreActions: false
    })
  },
  clickAdd() {
    let {
      formData
    } = this.data;
    if (formData.length >= 3)
      return showMsg('最多添加3个时间段');
    formData.push({
      startTime: "00:00:00",
      endTime: "23:59:59"
    });
    this.setData({
      formData
    })
  },
  clickDel(e) {
    console.log(e.currentTarget.dataset.index);
    let {
      formData
    } = this.data;
    formData.splice(e.currentTarget.dataset.index, 1);
    this.setData({
      formData
    })
  },
  DatePicker(e) {
    this.setData({
      showDatePicker: true,
      formDataindex: e.currentTarget.dataset.index,
      formDatatype: e.currentTarget.dataset.type,
      currentDate: e.currentTarget.dataset.currentdate,
      'value[0]': e.currentTarget.dataset.currentdate.charAt(0) == 0 ? e.currentTarget.dataset.currentdate.charAt(1) : e.currentTarget.dataset.currentdate.substring(0, 2),
      'value[1]': e.currentTarget.dataset.currentdate.charAt(3) == 0 ? e.currentTarget.dataset.currentdate.charAt(4) : e.currentTarget.dataset.currentdate.substring(3, 5),
      'value[2]': e.currentTarget.dataset.currentdate.charAt(6) == 0 ? e.currentTarget.dataset.currentdate.charAt(7) : e.currentTarget.dataset.currentdate.substring(6, 8),
    })
  },
  bindcancel(e) {
    this.setData({
      showDatePicker: false
    })
  },
  bindconfirm(e) {
    console.log(e.detail);
    let {
      formData
    } = this.data;
    if (this.data.formDatatype == 'startTime') {
      formData[this.data.formDataindex].startTime = e.detail
    } else {
      formData[this.data.formDataindex].endTime = e.detail
    }
    // formData[this.data.formDataindex].this.data.formDatatype=e.detail
    this.setData({
      showDatePicker: false,
      formData
    })
  },
  // 撤防时段
  async clickEdit() {
    const res = await reqGetByDeviceId(this.data.listItemInfo.id)
    if (res.code !== 20000) return showMsg(res.message)
    console.log(res);

    this.setData({
      show: true,
      formData: [],
    })
    if (res.data.rows.length == 0) return;
    let {
      formData
    } = this.data;
    formData = res.data.rows
    // formData = res.data.rows.map(item => {
    //     return {
    //         startTime: item.startTime.substring(0, 5),
    //         endTime: item.endTime.substring(0, 5)
    //     }
    // })
    this.setData({
      formData,
    })
  },
  clickHistory() {
    let info = JSON.stringify(this.data.listItemInfo)
    // console.log(info);
    // wx.navigateTo({
    //     url: `/pages/index-inside-page/device-detail/device-detail?info=${info}`,
    // })
    wx.navigateTo({
      url: `/packageA/pages/index-inside-page/history/history?info=${info}`,
    })
  },
  // clickProprietor() {
  //     let info = JSON.stringify(this.data.listItemInfo)
  //     // console.log(info);
  //     wx.navigateTo({
  //         url: `/packageA/pages/index-inside-page/proprietor/proprietor?info=${info}`,
  //     })
  // },
  onClose() {
    this.setData({
      show: false,
    });
  },
  //时间选择器
  bindChange: function (e) {
    const val = e.detail.value;
    const hours = this.data.hours[val[0]];
    const minutes = this.data.minutes[val[1]];
    const seconds = this.data.seconds[val[2]];
    console.log(`选择的时间为：${hours}:${minutes}:${seconds}`);
    this.setData({
      selectTime: `${hours}:${minutes}:${seconds}`
    })
  },
  // 时间取消
  closeDatePicker() {
    this.setData({
      showDatePicker: false
    })
  },
  // 确认时间
  addSearch() {
    let {
      formData,
      selectTime
    } = this.data;
    console.log(selectTime);
    if (this.data.formDatatype == 'startTime') {
      formData[this.data.formDataindex].startTime = selectTime
    } else {
      formData[this.data.formDataindex].endTime = selectTime
    }
    this.setData({
      showDatePicker: false,
      formData
    })
  },
  async bindtapShoudon() {
    let {
      formData
    } = this.data;
    let flag = false;
    formData.forEach(item => {
      if (item.startTime == item.endTime) {
        flag = true;
      }
      // item.startTime = item.startTime + ':00'
      // item.endTime = item.endTime + ':00'
    })
    if (flag) {
      showMsg('开始时间和结束时间相同，请修改！')
      // formData.forEach(item=>{
      //     item.startTime=item.startTime.slice(0,-3)//去掉字符串最后两个字符
      //     item.endTime=item.endTime.slice(0,-3)//去掉字符串最后两个字符
      // })
      return
    }
    const res = await reqDefenceupdate({
      deviceId: this.data.listItemInfo.id,
      formData
    })
    if (res.code !== 20000) {
      showMsg(res.message)
      // formData.forEach(item => {
      //     item.startTime = item.startTime.slice(0, -3) //去掉字符串最后两个字符
      //     item.endTime = item.endTime.slice(0, -3) //去掉字符串最后两个字符
      // })
      return
    }
    console.log(res);
    showMsg("设置成功")
    this.setData({
      show: false,
      showMoreActions: false
    });
  },
  // van-popup弹窗添加滚动条后导致背景内容跟随滑动
  touchmove() {},
  clickReplace() {
    this.setData({
      showreplace: true,
      newimei: ""
    })
  },
  replaceClose() {
    this.setData({
      showreplace: false,
    })
  },
  async bindreplace() {
    if (this.data.newimei == '') return showMsg('请输入设备编码')
    if (this.data.newimei == this.data.listItemInfo.imei) return showMsg('请输入新的设备编码')

    const resle = await reqCheckReplace({
      imei: this.data.newimei, //新
      imeiReplace: this.data.listItemInfo.imei, //旧
    })
    console.log(resle);
    let _this = this
    if (resle.code == 20001) {
      wx.showModal({
        title: '温馨提示',
        // content: `此操作会将已安装的设备进行拆除操作，是否继续？`,
        content: `此设备编码${_this.data.newimei}已安装，确认后该设备会进行拆除操作，是否继续？`,
        async success(res) {
          if (res.confirm) {
            const res = await reqDeviceReplace({
              imei: _this.data.newimei, //新
              imeiReplace: _this.data.listItemInfo.imei, //旧
              userId: app.globalData.userId,
              check: 1
            })
            if (res.code !== 20000) return showMsg(res.message)
            console.log(res);
            _this.setData({
              showreplace: false,
              showMoreActions: false,
            })
            await _this.getInitDataList()
            await _this.getStatistics()
            showMsg("更换成功")
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    } else if (resle.code == 14013) {
      showMsg('设备只能安装相同租户下')
    } else if (resle.code == 20000) {
      const res = await reqDeviceReplace({
        imei: _this.data.newimei, //新
        imeiReplace: _this.data.listItemInfo.imei, //旧
        userId: app.globalData.userId,
        check: 1
      })
      if (res.code !== 20000) return showMsg(res.message)
      console.log(res);
      _this.setData({
        showreplace: false,
        showMoreActions: false,
      })
      await _this.getInitDataList()
      await _this.getStatistics()
      showMsg("更换成功")
    } else {
      showMsg(resle.message)
    }
  },
  // 获取设备imei
  imeiChange(e) {
    let {
      value
    } = e.detail
    console.log(value);
    // if (value.length >= 3) {
    //     this.getDeviceByImei(value)
    // }
    if (value.length <= 0) {
      // 删除到没有时，清除imei和类型
      this.setData({
        newtype: "",
        newimei: ""
      })
      return
    }
    this.setData({
      newtype: "",
      newimei: value
    })
  },
  // 判断imei是否已存在
  // async getDeviceByImei(imei) {
  //     const res = await reqDeviceByImei(imei)
  //     if (res.code === 12020 || res.code === 12021) {
  //         // 清空操作
  //         this.setData({
  //             newimei:"",
  //             newtype:""
  //         })
  //         showMsg(res.message)
  //         return
  //     }
  //     if (res.code !== 20000) return showMsg(res.message)
  //     this.setData({
  //         newtype:res.data.row.productName,
  //         newimei:imei
  //     })
  // },
  imeiClear() {

  },
  newScan() {
    const that = this
    let qrcode = ''
    wx.scanCode({
      success(res) {
        qrcode = res.result;
        // console.log(qrcode);
        if (!qrcode) return showMsg('扫描失败，请重新扫描')
        if (qrcode.length >= 3) {
          if (that.isjson(qrcode)) {
            const result = JSON.parse(qrcode);
            // JSON字符格式
            that.setData({
              newimei: result.ID, //威视达康摄像机取值，后续看需求更改 lc
            })
          } else {
            // 非JSON格式
            that.setData({
              newimei: qrcode,
            })
          }
        } else {
          showMsg('扫描失败，请重新扫描')
          return
        }
      }
    })
  },
})